package prickworlds.physics;

/**
 * a rectangle shaped hitbox
 * 
 * @author Faruk Acibal, Richard Dziambor, Christian Holzreuter, Nicolas Winkler
 * 
 */
public class RectRigidBody extends RigidBody {
	float x;
	float y;
	float width;
	float height;

	public RectRigidBody() {
	}

	public RectRigidBody(float x, float y, float width, float height) {
		super();
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}

	public float getX() {
		return pos.x + x;
	}

	public float getY() {
		return pos.y + y;
	}

	/**
	 * determines, if this box overlaps another box
	 * 
	 * @param rrb
	 *            the other box
	 */
	@Override
	public boolean overlaps(RigidBody rigidBody) {
		if (!(rigidBody instanceof RectRigidBody)) {
			return false;
		}

		RectRigidBody rrb = (RectRigidBody) rigidBody;
		boolean overlapsX = getX() < rrb.getX() + rrb.width
				&& getX() + width > rrb.getX();
		boolean overlapsY = getY() < rrb.getY() + rrb.height
				&& getY() + height > rrb.getY();

		return overlapsX && overlapsY;
	}

	public boolean moveAside(RectRigidBody rrb) {
		if (!overlaps(rrb))
			return false;

		if (fix && !rrb.fix) {
			rrb.moveAside(this);
		}

		float xLeft = rrb.getX() + rrb.width - getX();
		float xRight = getX() + width - rrb.getX();

		float yTop = rrb.getY() + rrb.height - getY();
		float yBottom = getY() + height - rrb.getY();

		float xMin = Float.MAX_VALUE;
		float yMin = Float.MAX_VALUE;

		if (xLeft > 0)
			xMin = xLeft;
		if (xRight > 0 && xRight < xMin)
			xMin = xRight;

		if (yTop > 0)
			yMin = yTop;
		if (yBottom > 0 && yBottom < yMin)
			yMin = yBottom;

		if ((xLeft > 0 || xRight > 0) && xMin < yMin) {
			// needs x shifting

			if (xLeft < xRight) {
				if (rrb.fix)
					pos.x += xLeft / 2;
				else
					rrb.pos.x -= xLeft / 2;
				pos.x += xLeft / 2;
			} else {
				if (rrb.fix)
					pos.x -= xRight / 2;
				else
					rrb.pos.x += xRight / 2;
				pos.x -= xRight / 2;
			}
		} else if (yTop > 0 || yBottom > 0) {
			// needs y shifting

			if (yTop < yBottom) {
				if (rrb.fix)
					pos.y += yTop / 2;
				else
					rrb.pos.y -= yTop / 2;
				pos.y += yTop / 2;
			} else {
				if (rrb.fix)
					pos.y -= yBottom / 2;
				else
					rrb.pos.y += yBottom / 2;
				pos.y -= yBottom / 2;
			}
		}

		return true;
	}

	@Override
	public String toString() {
		return "RectRigidBody [height=" + height + ", width=" + width + ", x="
				+ x + ", y=" + y + ", fix=" + fix + ", pos=" + pos
				+ ", rigidBodyListeners=" + rigidBodyListeners + ", vel=" + vel
				+ "]";
	}
}
